package server

import (
	"gitee.com/chewel/hermes/pkg/ginx"
	"gitee.com/chewel/hermes/pkg/ginx/route"
	"github.com/gin-gonic/gin"
)

type HttpServer struct {
	g       gin.IRouter
	manager route.IRouterManager
}

func NewHttpServer(manager route.IRouterManager) ginx.IHttpServer {
	return &HttpServer{
		g:       gin.Default(),
		manager: manager,
	}
}

func (s *HttpServer) Use(middlewares ...ginx.HttpHandler) ginx.IHttpServer {
	for _, middleware := range middlewares {
		s.g.Use(middleware.Wrapper())
	}
	return s
}

func (s *HttpServer) Run(addr string) error {
	for _, info := range s.manager.Routers() {
		var handlers []gin.HandlerFunc
		if len(info.Middlewares) > 0 {
			for _, middleware := range info.Middlewares {
				handlers = append(handlers, middleware.Wrapper())
			}
		}
		handlers = append(handlers, info.Handler.Wrapper())
		s.g.Handle(info.Method.String(), info.Pattern, handlers...)
	}
	return s.Run(addr)
}
